<?php
/**
 * article actions.
 *
 * @package    explications_informatiques
 * @subpackage article
 * @author     Guimezanes Cyrille
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class articleActions extends sfActions
{
  private function send_mail_to_followers($article, $type)
  {
	  if(false && sfContext::getInstance()->getConfiguration()->getEnvironment() != 'dev' )
            {
				$q = Doctrine_Query::create()
	 				->from('Follow')
					->where("id_asso = ?",$article["id_asso"]);
				$follows = $q->execute();
				
				foreach ($follows as $follow)
				{
					$message = $this->getMailer()->compose(
						  array('contact@explications-informatiques.fr' => "L'équipe d'explications-informatiques.fr"),
						  $follow["email"],
						  'Un article que vous suivez à été modifié',
							"
							Nous vous informons que l'article nommé: ".$article["title"]." à subit une modification (".$type.").
							
							Vous pouvez consulter l'article sur <a href='http://explications-informatiques.fr/index.php/a/".$article["id_asso"]."/".sfCoreAutoload::sluggify($article["title"])."'>".$article["title"]."</a> .
							
							Vous pouvez vous déinscrire de cette lettre d'information en cliquant <a href='http://explications-informatiques.fr/index.php/follow/delete/".$follow["id"]."' target='_blank'>sur ce lien</a>
							
							A trés bientôt sur http://explications-informatiques.fr! 
							"
						);
					$message->setContentType("text/html");
					$this->getMailer()->send($message);
				}
			}
  }
  public function executeIndex(sfWebRequest $request)
  {
     $q = Doctrine_Query::create()
	 	->from('articles n')
		->leftJoin('n.Categories')
		->leftJoin('n.Assoplatform c')
		->leftJoin('c.Commentaires')
		->leftJoin('c.Notes')
		->leftJoin('n.Tags')
		->leftJoin('c.Platform')
		->leftJoin('c.Platform_4')
		->where("n.online = ?","1")
		->orderBy ('n.idarticles DESC');

	  $this->pager = new sfDoctrinePager(
		'Articles',
		10//nb résultats par pages
	  );
	  $this->pager->setQuery($q);
	  $this->pager->setPage($request->getParameter('page', 1));
	  $this->pager->init();
	  
	  $this->articles = $this->pager->getResults();
	  $this->nb_coms = array();
		foreach($this->articles as $art)
		{
			$nb = 0;
			foreach($art["Assoplatform"] as $asso)
			{
				$nb += count($asso["Commentaires"]);
			}
			$this->nb_coms[] = $nb;
		}
  }
  public function executeSelectArticle(sfWebRequest $request)
  {
	  if($request->getParameter('idasso'))
	  {
		  $id_asso = $request->getParameter('idasso');
	  }
	  else
	  {
		 $browscap = $this->getUser()->getBrowscap();
		
		 $major = NULL;
		 $version_major = NULL;
		 if($this->getUser()->isAuthenticated())
		 	$user = $this->getUser()->getGuardUser()->getId();
		 else
		 	$user = "-1";
		 $user_platform = $this->getUser()->getPlatforms($user,$user != "-1",$browscap);
		 
		 $asso_plaforms_major = array();
		 $asso_plaforms_version_major = array();
		 
		 if($request->getParameter('major') != "")
			$major = $request->getParameter('major');
		 else
		 {
		   $add_sql = "";
		   $nb = count($user_platform);
		   for($i = 0; $i < $nb ; $i++)
			  if($i != ($nb - 1))
				  $add_sql .= "major.id = ".$user_platform[$i]["id_platform"]." OR ";
			  else
				  $add_sql .= "major.id = ".$user_platform[$i]["id_platform"];
			
			if($nb > 0)
			{
				 		
				 $q = Doctrine_Query::create()
					->from('assoplatform ap')
					->leftJoin('ap.Platform major')
					->leftJoin('ap.Platform_4')
					->leftJoin('ap.Plateformversiongroup gp1')
					->leftJoin('gp1.Plateformversion')
					->leftJoin('ap.Plateformversiongroup_5 gp2')
					->leftJoin('gp2.Plateformversion')
					->where('ap.id_article = ?',$request->getParameter('idarticles'))
					->andWhere($add_sql);
				$asso_plaforms_major = $q->execute();
			}
		 }	

			 if($request->getParameter('version_major') != "")
				$version_major = $request->getParameter('version_major');
			 else
			 	foreach($asso_plaforms_major as $asso)
					 	foreach($user_platform as $user_plat)
						 	foreach($asso["Plateformversiongroup"] as $version)
								 if($version["Plateformversion"]["id"] == $user_plat["version"])
								 	$asso_plaforms_version_major[] = $asso;

		 $id_asso = -1;
		 
		 if(empty($major))
		 {
			 if(count($asso_plaforms_version_major) == 1)
			 	$id_asso = $asso_plaforms_version_major[0]["idassoplatform"];
			 elseif(count($asso_plaforms_major) == 1)
			 	$id_asso = $asso_plaforms_major[0]["idassoplatform"]; 
		 }
		 else
		 {
			$q = Doctrine_Query::create()
					->from('assoplatform ap')
					->where('ap.id_article = ?', $request->getParameter('idarticles'))
					->andWhere('ap.id_major = ?', $major);
			$temp = $q->execute();
			$this->articles = $temp[0];
			$id_asso = $temp[0]["idassoplatform"];
			
			
			// gestion des relations entres les articles
	  $relations = $this->getUser()->getAttribute('relationsArticle');
		if(is_array($relations))
		 {
			 foreach($relations as $relation)
			 {
				 if($relation != $this->articles["Articles"]["idarticles"])
				 {
					 $relat = Doctrine_Query::create()
						->from("relationsarticles")
						->where("id_art_act = ?", $this->articles["Articles"]["idarticles"])
						->andwhere("id_art_link = ?", $relation);
					 $nb_res = $relat->count();
					 
					 if($nb_res == 0)
					 {
						 $t = new Relationsarticles();
						 $t->setIdArtAct($this->articles["Articles"]["idarticles"]);
						 $t->setIdArtLink($relation);
						 $t->setFrequence(1);
						 $t->save();
					 }
					 else
					 {
						$res = $relat->execute();
					 	$res[0]->setFrequence(intval($res[0]->getFrequence()) + 1);
						$res->save();
					 }
						
					 
				 }
			 }
			 if(!in_array($this->articles["Articles"]["idarticles"],$relations))
			 	$relations[] = $this->articles["Articles"]["idarticles"];
			 if(count($relations) < 3)
			 	$this->getUser()->setAttribute('relationsArticle',$relations);
			 else
			 	$this->getUser()->setAttribute('relationsArticle',array($this->articles["Articles"]["idarticles"]));
		 }
		 else
		 	$this->getUser()->setAttribute('relationsArticle',array($this->articles["Articles"]["idarticles"]));

	  //fin relation
	  	$this->articles["Articles"]["hits"] = intval($this->articles["Articles"]["hits"] + 1);
		$this->articles["Articles"]->save();
			
			
		 }
	  }
	  
	  if ($id_asso > 0)
	  	$this->redirect("@view_article?idasso=".$id_asso."&title=".$request->getParameter('title'));
	  elseif(!$request->getParameter('major'))
		$this->redirect("@view_options?idarticles=".$request->getParameter('idarticles'));
	  else
	  	$this->forward404();
		
  }
  public function executeShow(sfWebRequest $request)
  {
	 		
		 $q = Doctrine_Query::create()
		->from('assoplatform ap')
		->leftJoin('ap.Articles n')
		->leftJoin('n.Tags')
		->leftJoin('n.Categories')
		->leftJoin('ap.Notes na')
		->leftJoin('n.Articlesreferences')
		->leftJoin('n.Articlessources')
		->leftJoin('n.Relationsarticles ra')
		->leftJoin('ra.Articles_2')
		->where('ap.idassoplatform = ?', $request->getParameter('idasso'))
		->andWhere("n.online = ?","1")
		->limit('1');
		$this->articles  = $q->fetchOne();
		
		
		$q = Doctrine_Query::create()
		->from('Commentaires c')
		->leftJoin('c.SfGuardUserProfile sp')
		->leftJoin('sp.User')
		->where('id_asso = ?',$this->articles["idassoplatform"]);
		
		$this->pager = new sfDoctrinePager(
			'Commentaires',
			10
	);
		 
		 $this->pager->setQuery($q);
		 $this->pager->setPage($request->getParameter('page', 1));
		 $this->pager->init();
	 	 $this->commentaires = $this->pager->getResults();
		 
		$total = 0;
		foreach($this->articles["Notes"] as $note)
			$total += intval($note["note"]);
		if(count($this->articles["Notes"]) > 0)
			$this->Moyenne = round($total/count($this->articles["Notes"]),2);
		else
			$this->Moyenne = "-";
		
		$q = Doctrine_Query::create()
		->from('revisions n')
		->leftJoin('n.Assoplatform ap')
		->leftJoin('ap.Articles')
		->leftJoin('n.Flags f')
		->leftJoin('f.Defsflags')
		//->where('n.validate = ?', '1')
		->andwhere('n.id_asso_platform = ?', $request->getParameter('idasso'))
		->orderBy('n.idrevisions desc')
		->limit(1);
		
		$this->revisions = $q->fetchOne();
		
		if ($this->getUser()->hasCredential("MOD_REVISION"))
		{
			$this->revisions["Assoplatform"]["view_by_mode"] = "1";
			foreach ($this->revisions as $revision)
				$revision["validate"] = "1";
			$this->revisions->save();
		}
		
		$this->revision = $this->revisions;
		
		$texte = file_get_contents("revisions/".$this->revisions["Assoplatform"]["idassoplatform"]."_".$this->revisions["idrevisions"].".txt");
		$this->texte = $texte;
		$this->content_table = array();
		$this->texte = preg_replace('#<p class="(titre_de_section|titre_de_sous_section)">(.+)([A-Za-z0-9àáâãäåçèéêëìíîïðòóôõöùúûüýÿ&/,\?:\!;%\*\-\' ]+)(</[^>]+>)*</p>#iU','<p class="$1" id="$3">$3</p>',$this->texte);		
		preg_match_all('#<p class="(titre_de_section|titre_de_sous_section)" id="(.*)">(.*)</p>#U', $this->texte, $this->content_table);
		$this->forward404Unless($this->articles);
	
  }

  public function executeNew(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_ARTICLE"),"headers","forbidden");
    $this->form = new ArticlesForm();
  }
  
  public function executeCreate(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_ARTICLE"),"headers","forbidden");
    $this->forwardUnless($request->isMethod(sfRequest::POST),"headers","forbidden");

    $this->form = new ArticlesForm();

    $this->processFormNew($request, $this->form);

	
    $this->setTemplate('new');
  }
  public function executeVersion(sfWebRequest $request)
  {
	  $this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_VERSION"),"headers","forbidden");
	  $this->form = new ArticlesaddForm();
	  $this->form->setDefault('id', $request->getParameter('id'));
  }
  public function executeAdd(sfWebRequest $request)
  {
     $this->forwardUnless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT),"headers","forbidden");

    $this->form = new ArticlesaddForm();

    $this->processFormAdd($request, $this->form);

    $this->setTemplate('version');
	
  }
  
  public function executeEdit(sfWebRequest $request)
  {
	if(is_file("../cache/draft_".$request->getParameter('id').".cache"))
	{
		$infos = json_decode(file_get_contents("../cache/draft_".$request->getParameter('id').".cache"));
		if(intval($infos->time) > time() + 15)
		 	$this->redirect("headers/isedited?id_asso=".$request->getParameter('id')."&user=".$infos->user."&date=".$infos->date);
		else
			unlink("../cache/draft_".$request->getParameter('id').".cache");
	}
	
    $this->forwardUnless($this->getUser()->hasCredential("AJOUT_ARTICLE"),"headers","forbidden");
	$q = Doctrine_Query::create()
		->from('Revisions r')
		->andwhere('r.id_asso_platform = ?', $request->getParameter('id'))
		->orderBy('r.idrevisions desc');
	$texte = $q->fetchOne();
	$this->id_asso = $request->getParameter('id');
	$this->forward404Unless($texte);
	$this->form = new ArticleseditForm();
	$this->form->setDefault('texte', file_get_contents("revisions/".$request->getParameter('id')."_".$texte["idrevisions"].".txt"));
	$this->form->setDefault('id', $request->getParameter('id'));
	
	
  }
  public function executeUpdatedraft(sfWebRequest $request)
  {
	  if ($request->isXmlHttpRequest())
	  {
		$values = array(
						"date" => date("d-m-Y h:i:s"),
						"user" => $this->getUser()->getGuardUser()->getUsername(),
						"time" => time()
						);
	  	file_put_contents("../cache/draft_".$request['id'].".cache", json_encode($values));
		echo date("d-m-Y h:i:s");
		die();
	  }
  }
  public function executeLoaddraft(sfWebRequest $request)
  {
	  if ($request->isXmlHttpRequest())
	  {
	  	echo file_get_contents("../cache/draft_".$request['id'].".cache");
		die();
	  }
  }
  public function executeDeletedraft(sfWebRequest $request)
  {
	  if ($request->isXmlHttpRequest())
	  {
	  	unlink("../cache/draft_".$request['id'].".cache");
		die();
	  }
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forwardUnless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT),"headers","forbidden");
    
	//$this->forward404Unless($articles = Doctrine_Core::getTable('Assoplatform')->find(array($request->getParameter('id'))), sprintf('Object articles does not exist (%s).', $request->getParameter('idarticles')));
    $this->form = new ArticleseditForm();
    $this->processFormEdit($request, $this->form);
	
    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->hasCredential("SUPPR_ARTICLE"),"headers","forbidden");

    $q = Doctrine_Query::create()
		->from('articles a')
		->leftJoin("a.Assoplatform r")
		->leftJoin("r.Revisions")
		->where('a.idarticles = ?',$request->getParameter('id'));
		
	$res = $q->execute();
	
	foreach ($res["Assoplatform"] as $asso)	
		foreach($asso["Revisions"] as $revision)
			unlink("/revisions/".$asso["idassoplatform"]."_".$texte["idrevisions"].".txt");		
	
	$this->getUser()->setAttribute('relationsArticle',array());
	$res->delete();
	sfCoreAutoload::logElem("Supression d'un article - id:".$request->getParameter('id'), $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
	$this->getUser()->setFlash("info","Article supprimé");
    $this->redirect('article/index');
  }
  public function executeDeleterevision(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->hasCredential("SUPPR_REVISION"),"headers","forbidden");
	$q = Doctrine_Query::create()
		->from('revisions')
		->where('id_asso_platform = ?',$request->getParameter('id2'));
	$nb = $q->count();
	if ($nb > 1)
	{
		$this->forward404Unless($articles = Doctrine_Core::getTable('Revisions')->find(array($request->getParameter('id'))), sprintf('Object articles does not exist (%s).', $request->getParameter('id')));
		$articles->getSfGuardUserProfile()->decrPoint(160, "Suppression d'une de vos contribution");
		$articles->delete();
		unlink("/revisions/".$request->getParameter('id2')."_".$request->getParameter('id').".txt");
		$this->getUser()->setFlash("info","Révision supprimée");
		if ($cache = $this->getContext()->getViewCacheManager())
		  {
			 $cache->remove('article/index');
			 $cache->remove('headers/modepanel');
			 $cache->remove('article/show?id_asso='.$request->getParameter('id2'));
		  }
		  sfCoreAutoload::logElem("Supression d'une revision - asso:".$request->getParameter('id2')." revision:".$request->getParameter('id'), $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
	}
	else
		$this->getUser()->setFlash("err","Vous ne pouvez pas supprimer la revision initiale");
	
	$this->redirect('@show_article?title=article&idasso='.$request->getParameter('id2'));
  }
  public function executeDeleteversion(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->hasCredential("SUPPR_VERSION"),"headers","forbidden");
	$q = Doctrine_Query::create()
		->from('assoplatform a')
		->where('a.id_article = ?',$request->getParameter('id2'));
	$nb = $q->count();
	if ($nb > 1)
	{
		$q = Doctrine_Query::create()
		->from('assoplatform a')
		->leftJoin("a.Revisions r")
		->where('a.idassoplatform = ?',$request->getParameter('id'));
		
		$res = $q->execute();
		$this->getUser()->setAttribute('relationsArticle',array());
		foreach($res[0]["Revisions"] as $revision)
			unlink("/revisions/".$request->getParameter('id2')."_".$revision["idrevisions"].".txt");		
		$res->delete();
		$this->getUser()->setFlash("info","Version supprimée");
		if ($cache = $this->getContext()->getViewCacheManager())
		  {
			 $cache->remove('article/index');
			 $cache->remove('headers/modepanel');
			 $cache->remove('main/index');
			 $cache->remove('article/show?id_asso='.$request->getParameter('id2'));
		  }
		  //log de l'action en cours
	  sfCoreAutoload::logElem("Supression d'une version - asso:".$request->getParameter('id2')." revision:".$revision["idrevisions"], $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
	}
	else
		$this->getUser()->setFlash("err","Vous ne pouvez pas supprimer la version initiale");
	$this->redirect('@show_article?title=article&idasso='.$request->getParameter('id2'));

  }
  public function executeOptions(sfWebRequest $request)
  {
	  
	  $q = Doctrine_Query::create()
		->from('assoplatform n')
		->leftJoin('n.Plateformversiongroup pg1')
		->leftJoin('pg1.Plateformversion')
		->leftJoin('n.Plateformversiongroup_5 pg2')
		->leftJoin('pg2.Plateformversion')
		->leftJoin('n.Platform')
		->leftJoin('n.Platform_4')
		->leftJoin('n.Articles')
		->where('n.id_article = ?', $request->getParameter('idarticles'));
		
	  	 $this->pager = new sfDoctrinePager(
			'Assoplatform',
			10//nb résultats par pages
		  );
		  $this->pager->setQuery($q);
		  $this->pager->setPage($request->getParameter('page', 1));
		  $this->pager->init();
	  	 $this->id_art = $request->getParameter('idarticles');
	 	 $this->options = $this->pager->getResults();
		 if ($q->count() == 1)
	  		$this->redirect("@show_article?idasso=".$this->options[0]["idassoplatform"]."&title=".sfCoreAutoload::sluggify($this->options[0]["Articles"]["title"]));
  }
  public function executeViewrevision(sfWebRequest $request)
  {
	  $q = Doctrine_Query::create()
		->from('revisions u')
		->leftJoin('u.SfGuardUserProfile p')
		->leftJoin('p.User d')
		->where('u.id_asso_platform = ?',$request->getParameter('id'))
		->orderBy('u.date_creation desc');
	  $this->revisions = $q->execute();
	  $this->asso = $request->getParameter('id');
  }
  public function executeCompare(sfWebRequest $request)
  {
	  $before = file("Revisions/".$request["asso"]."_".$request["before"].".txt");
	  $after = file("Revisions/".$request["asso"]."_".$request["after"].".txt");
	  $this->numBefore = $request["before"];
	  $this->numAfter = $request["after"];
	  $this->HTMLView = ($request["html"] != 1);
	  $this->diffBefore = array();
	  $this->diffAfter = array();
	  $this->asso = $request["asso"];
	  
	  for($i = 0; $i < max(array(count($before),count($after))); $i++)
	  {
		  if(isset($before[$i]) && isset($after[$i]) && strcoll (trim($before[$i]),trim($after[$i])) != 0)
		  {
			  $this->diffBefore[] =  $before[$i];
			  $this->diffAfter[] = $after[$i];
		  }
		  elseif(!isset($before[$i]) && isset($after[$i]))
		  {
			  $this->diffBefore[] =  "";
			  $this->diffAfter[] = $after[$i];
		  }
		  elseif(isset($before[$i]) && !isset($after[$i]))
		  {
			  $this->diffBefore[] =  $before[$i];
			  $this->diffAfter[] = "";
		  }
	  }
	  
  }
  private function regVersion($request,$platform,$type)
  {
	  if($request->getParameter('choices_'.$type) == "1")
	  {
		  $groupe_version = array();
		  $names = $request->getParameter('new_version_name_'.$type);
		  
		  for($i = 0; $i < count($names);$i++)
		  {
			  //on enregistre la nouvelle version
			  $version = new Plateformversion();
			  $version->setPlatform($platform);
			  $version->setVersion($names[$i]);
			  $version->save();
			  
			  
			  if(is_array($request->getParameter('new_version_'.$type)) 
			  	&& in_array($i,$request->getParameter('new_version_'.$type)))
			  		$groupe_version[] = $version->getId();
		  }
		  //var_dump($groupe_version);
		  return $groupe_version;
	  }
	  
	  	return array();
  }
  
  private function createGroup($num,$addedplatform,$request,$type)
  {
	  if(!$request->getParameter('version_'.$type)) $tabToMerge = array();
	  else $tabToMerge = $request->getParameter('version_'.$type);
	  
	  $tabs = array_merge($addedplatform,$tabToMerge);
	  $i = 0;
	  foreach($tabs as $majorGroup)
	  {
		  $groupe = new Plateformversiongroup();
		  $groupe->setIdGroup($num);
		  $groupe->setVersion($majorGroup);
		  $groupe->save();
		  $i++;
	  }
	  if($i > 0)
	  	return array($tabs,$num++,$groupe);
	  else
	  	return array($tabs,$num);
  }
  private function regNewPlatform($request,$type)
  {
	  if($request->getParameter('new_'.$type))
	  {
		  $newPlat = new Platform();
	  }
  }
  
  protected function processFormAdd(sfWebRequest $request, sfForm $form)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_VERSION"),"headers","forbidden");
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	 
	  $q = Doctrine_Query::create()
	  	->from("articles")
		->where('idarticles = ?',$request["articles"]["id"]);
	  
	  $article = $q->fetchOne();
	  
		$q = Doctrine_Query::create()
	  	->select("MAX(id_group) as max")
		->from('plateformversiongroup');
	  $max = $q->execute();
	  $nummax = ($max->getFirst()->max + 1);
	  
	  $platformmajor = Doctrine::getTable('Platform')->find($request["articles"]["major"]);
	  $newgroupemajor = $this->regVersion($request,$platformmajor,"major");
	  $groupemajor = $this->createGroup($nummax,$newgroupemajor,$request,"major");
	  
	  $platformminor = Doctrine::getTable('Platform')->find($request["articles"]["minor"]);
	  $newgroupeminor = $this->regVersion($request,$platformminor,"minor");
	  $groupeminor = $this->createGroup($groupemajor[1],$newgroupeminor,$request,"minor"); 
	  
	  
	  $this->regNewPlatform($request,"major");
	  $this->regNewPlatform($request,"minor");
	  
	  $assoplat = new Assoplatform();
	  $assoplat->setIdArticle($article);
	  if(!empty($platformmajor))
	  {
		  $assoplat->setIdMajor($platformmajor);
		  if(isset($groupemajor[2]))
			 $assoplat->setIdVersionMajor($groupemajor[1]);
	  }
	  if(!empty($platformminor))
	  {
		  $assoplat->setIdMinor($platformminor);
		 
		  if(isset($groupeminor[2]))
			  $assoplat->setIdVersionMinor($groupeminor[1]);
	  }
		  
	  $assoplat->save();
	  
	  //on creer une nouvelle révision
	  $revision = new Revisions();
	  $revision->setIdAssoPlatform($assoplat);
	  $revision->setIdAuteur($this->getUser()->getGuardUser()->getId());
	  $revision->setDateCreation(date("Ymdhis"));
	  $revision->setValidate(0);
	  $revision->setCommentaire("Création de l'article");
	  $revision->save();
	  
	  $this->getUser()->updatePoint(100, "Ajout d'une version");
	  //on parse le texte pour extraire les references et les sources
	  //on ajoute d'entuelle nouvelle reference et sources
	  file_put_contents("revisions/".$assoplat["idassoplatform"]."_".$revision->getIdrevisions().".txt",$request["articles"]['texte']);
	  
	  $flag = new Flags();
	  $flag->setIdRevision($revision->getIdrevisions());
	  $flag->setIdFlag(1);
	  $flag->save();
	  if ($cache = $this->getContext()->getViewCacheManager())
	  {
		 $cache->remove('article/index');
		 $cache->remove('headers/modepanel');
		 $cache->remove('main/index');
		 $cache->remove('article/show?id_asso='.$assoplat["idassoplatform"]);
		 $cache->remove('article/option?idarticles='.$request["articles"]["idarticles"]);
	  }
	  $this->send_mail_to_followers(array("title" => $article->getTitle(), "id_asso" => $assoplat["idassoplatform"]), "Ajout d'une nouvelle version de l'article");
	  //log de l'action en cours
	  sfCoreAutoload::logElem("Ajout d'une version - asso:".$assoplat["idassoplatform"]." revision:".$revision->getIdrevisions(), $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
	  $this->getUser()->setFlash("info","Une nouvelle version à été ajoutée");
	  $this->redirect('@show_article?title=article&idasso='.$assoplat["idassoplatform"]);

	}
  }
  
  protected function processFormEdit(sfWebRequest $request, sfForm $form)
  {
	
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_REVISION"),"headers","forbidden");
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	
	  $revision = new Revisions();
	  $revision->setIdAssoPlatform($request["articles"]["id"]);
	  $revision->setIdAuteur($this->getUser()->getGuardUser()->getId());
	  $revision->setDateCreation(date("Ymdhis"));
	  $revision->setValidate(0);
	  $revision->setCommentaire($request["articles"]["commentaire"]);
	  $revision->save();
	  
	  $this->getUser()->updatePoint(80, "Ajout d'une révision");
	  
	  file_put_contents("revisions/".$request["articles"]["id"]."_".$revision->getIdrevisions().".txt",$request["articles"]["texte"]);

	  $flag = new Flags();
	  $flag->setIdRevision($revision->getIdrevisions());
	  $flag->setIdFlag(1);
	  $flag->save();
	  
	  if ($cache = $this->getContext()->getViewCacheManager())
	  {
		 $cache->remove('article/index');
		 $cache->remove('headers/modepanel');
		 $cache->remove('article/show?id_asso='.$request["articles"]["id"]);
	  }
	  
	  if (is_file ("../cache/draft_".$request["articles"]["id"]."cache"))
	  	unlink("../cache/draft_".$request["articles"]["id"]."cache");
	  //die($request["articles"]["id"]."   ".$revision->getAssoplatform()->getArticles()->getTitle());
	  $this->send_mail_to_followers(array("title" => $revision->getAssoplatform()->getArticles()->getTitle(), "id_asso" => $request["articles"]["id"]), "Modification du texte de l'article");
	  //log de l'action en cours
	   
	  sfCoreAutoload::logElem("Ajout d'une révision - asso:".$request["articles"]["id"]." revision:".$revision->getIdrevisions(), $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
	  
	  $this->getUser()->setFlash("info","Votre modification à été effectuée");
	 
	  $this->redirect('@show_article?title=article&idasso='.$request["articles"]["id"]);
	}
	
	
  }
  protected function processFormNew(sfWebRequest $request, sfForm $form)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_ARTICLE"),"headers","forbidden");
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
	  /*var_dump($request->getParameter('choices_type'));
	  var_dump($request->getParameter('version'));
	  var_dump($request->getParameter('new_version'));
	  var_dump($request->getParameter('new_version_name'));*/
    if ($form->isValid())
    {
		$q = Doctrine_Query::create()
		 ->from('articles m')
		 ->where('m.title = ?',$request["articles"]["title"]);	
	  if($q->count() == 0)
	  {
		  $article = new Articles();
		  $article->setDateCreation(date("Ymdhis"));
		  $article->setOnline(1);
		  $article->setCategory($request["articles"]["category"]);
		  $article->setDescription($request["articles"]["description"]);
		  $article->setTitle($request["articles"]["title"]);
		  $article->save();
	 
		  $tags = explode(" ",$request["articles"]["tags"]);
		  
		  foreach($tags as $tag)
		  {
			  $tag_reg = new Tags();
			  $tag_reg->setTag($tag);
			  $tag_reg->setIdArticle($article);
			  $tag_reg->save();
		  }
	   }
	  else
	  {
		  
		  $article = $q->fetchOne();
	  }
	  
	  $q = Doctrine_Query::create()
	  	->select("MAX(id_group) as max")
		->from('plateformversiongroup');
	  $max = $q->execute();
	  $nummax = ($max->getFirst()->max + 1);
	  
	  $platformmajor = Doctrine::getTable('Platform')->find($request->getParameter("major"));
	  $newgroupemajor = $this->regVersion($request,$platformmajor,"major");
	  $groupemajor = $this->createGroup($nummax,$newgroupemajor,$request,"major");
	  
	  $platformminor = Doctrine::getTable('Platform')->find($request->getParameter("minor"));
	  $newgroupeminor = $this->regVersion($request,$platformminor,"minor");
	  $groupeminor = $this->createGroup($groupemajor[1],$newgroupeminor,$request,"minor"); 
	  
	  
	  $this->regNewPlatform($request,"major");
	  $this->regNewPlatform($request,"minor");
	  
	  $assoplat = new Assoplatform();
	  $assoplat->setIdArticle($article);
	  if(!empty($platformmajor))
	  {
	  	$assoplat->setIdMajor($platformmajor);
		  if(isset($groupemajor[2]))
			 $assoplat->setIdVersionMajor($groupemajor[1]);
	  }
	  if(!empty($platformminor))
	  {
	  	$assoplat->setIdMinor($platformminor);
	 
		  if(isset($groupeminor[2]))
			  $assoplat->setIdVersionMinor($groupeminor[1]);
	  }
		  
	  $assoplat->save();
	  
	  //on creer une nouvelle révision
	  $revision = new Revisions();
	  $revision->setIdAssoPlatform($assoplat);
	  $revision->setIdAuteur($this->getUser()->getGuardUser()->getId());
	  $revision->setDateCreation(date("Ymdhis"));
	  $revision->setValidate(0);
	  $revision->setCommentaire("Création de l'article");
	  
	  $revision->save();
	  
	  $this->getUser()->updatePoint(100, "Ajout d'un article");
	  //on parse le texte pour extraire les references et les sources
	  //on ajoute d'entuelle nouvelle reference et sources
	  file_put_contents("revisions/".$assoplat["idassoplatform"]."_".$revision->getIdrevisions().".txt",$request["articles"]['texte']);
	  if ($cache = $this->getContext()->getViewCacheManager())
	  {
		 $cache->remove('article/index');
		 $cache->remove('headers/modepanel');
		 $cache->remove('main/index');
		 $cache->remove('article/show?id_asso='.$assoplat);
	  }
	  //log de l'action en cours
	  sfCoreAutoload::logElem("Ajout d'un nouvel article asso:".$assoplat ." revision".$revision->getIdrevisions(), $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
	  
	  $flag = new Flags();
	  $flag->setIdRevision($revision->getIdrevisions());
	  $flag->setIdFlag(1);
	  $flag->save();

	  
	  $this->getUser()->setFlash("info","L'article à été créé avec succés!");
      $this->redirect('@show_article_by_id?title='.sfCoreAutoload::sluggify($article->getTitle()).'&idarticles='.$article->getIdarticles());
    }
  }
  
  public function executeUpdatelist(sfWebRequest $request)
  {
	   if ($request->isXmlHttpRequest())
		{
			$idplatforme = $request->getParameter('id');
			
			$q = Doctrine_Query::create()
				->from('plateformversion n')
				->where('n.platform = ?', $idplatforme)
				->orderBy('n.version asc');
			$this->brute_choices = $q->execute();
			$this->type = $request->getParameter('type');
			return $this->renderPartial('choiceversion');
		}

  }
  public function executeJrating(sfWebRequest $request)
  {
	   
	   $aResponse['error'] = false;
	   $aResponse['message'] = '';
	   
	   
	   if ($request->isXmlHttpRequest())
		{		
				$id = intval($request['idBox']);
				$rate = floatval($request['rate']);
				//$idplatforme = $request->getParameter('id');
				$vote = new Notes();
				$vote->setIdArticle($id);
				$vote->setNote($rate);
				$vote->setIdClient($this->getUser()->getGuardUser()->getId());
				$vote->save();
				if ($cache = $this->getContext()->getViewCacheManager())
				  {
					$cache->remove('article/index*');
					$cache->remove('article/show?id_asso='.$id);
				  }
				$aResponse['error'] = true;
				$aResponse['message'] = 'Your rate has been successfuly recorded. Thanks for your rate :)';
		}
		else
		{
			$aResponse['error'] = true;
			$aResponse['message'] = '"action" post data not equal to \'rating\'';
		}
		
		echo json_encode($aResponse);
		die();

  }
  public function executePdf(sfWebRequest $request)
  {
	  $this->forwardUnless($this->getUser()->hasCredential("VIEW_PDF"),"headers","forbidden");
	  $config = sfTCPDFPluginConfigHandler::loadConfig();
    //sfTCPDFPluginConfigHandler::includeLangFile($this->getUser()->getCulture());

     $q = Doctrine_Query::create()
		->from('assoplatform ap')
		->leftJoin('ap.Articles n')
		->leftJoin('ap.Revisions r')
		->leftJoin('n.Tags')
		->leftJoin('ap.Notes na')
		->leftJoin('n.Articlesreferences')
		->leftJoin('n.Articlessources')
		->leftJoin('n.Relationsarticles ra')
		->leftJoin('ra.Articles_2')
		->where('ap.idassoplatform = ?', $request->getParameter("id"))
		->orderBy('r.idrevisions DESC')
		->limit('1');
		
	$article = $q->fetchOne();
    $doc_title    = $article["Articles"]["title"];
    $doc_subject  = $article["Articles"]["description"];
    if(is_array($article["Articles"]["Tags"]))
		$doc_keywords = implode(",",$article["Articles"]["Tags"]);
	else
		$doc_keywords = "";
    $htmlcontent  = "<h1>".$article["Articles"]["title"]."</h1><br>";
	
	$htmlcontent  .= file_get_contents("Revisions/".$article["idassoplatform"]."_".$article["Revision"][0]["idrevisions"].".txt");

    //create new PDF document (document units are set by default to millimeters)
    $pdf = new sfTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);

    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor(PDF_AUTHOR);
    $pdf->SetTitle($doc_title);
    $pdf->SetSubject($doc_subject);
    $pdf->SetKeywords($doc_keywords);

    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

    //set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

    //set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set image scale factor

    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    //initialize document
    $pdf->AliasNbPages();
    $pdf->AddPage();

    $pdf->writeHTML($htmlcontent , true, 0);

    
    ob_end_clean();
	$pdf->Output();

    // Stop symfony process
    throw new sfStopException();
  }
  public function executeRss(sfWebRequest $request)
  {
	  $feed = new sfRssFeed();
	  $feed->setTitle('Les derniers articles publiés');
	  $feed->setLink('http://explications-informatiques.fr');
	  $feed->setAuthorEmail('contact@explications-informatiques.fr');
	  $feed->setAuthorName('Explications Informatiques');
	
	 
	
	  $q = Doctrine_Query::create()
	 	->from('articles n')
		->orderBy("n.idarticles DESC")
	    ->limit(15);
	  $posts = $q->execute();
	
	  foreach ($posts as $post)
	  {
		$item = new sfFeedItem();
		$item->setTitle($post["title"]);
		$item->setLink("@show_article_by_id?title=".sfCoreAutoload::sluggify($post["title"])."&idarticles=".$post["idarticles"]);
		//$item->setAuthorName($post->getAuthor()->getName());
		//$item->setAuthorEmail($post->getAuthor()->getEmail());
		$item->setPubdate(date("U",strtotime($post["date_creation"],time())));
		$item->setUniqueId($post["idarticles"]);
		$item->setDescription($post["description"]);
	
		$feed->addItem($item);
	  }
	
	  $this->feed = $feed;
  }
  public function executeAtom(sfWebRequest $request)
  {
	  $feed = new sfAtom1Feed();
	  $feed->setTitle('Les derniers articles publiés');
	  $feed->setLink('http://explications-informatiques.fr');
	  $feed->setAuthorEmail('contact@explications-informatiques.fr');
	  $feed->setAuthorName('Explications Informatiques');
	
	 
	
	  $q = Doctrine_Query::create()
	 	->from('articles n')
		->orderBy("n.idarticles DESC")
	    ->limit(15);
	  $posts = $q->execute();
	
	  foreach ($posts as $post)
	  {
		$item = new sfFeedItem();
		$item->setTitle($post["title"]);
		$item->setLink("@show_article_by_id?title=".sfCoreAutoload::sluggify($post["title"])."&idarticles=".$post["idarticles"]);
		//$item->setAuthorName($post->getAuthor()->getName());
		//$item->setAuthorEmail($post->getAuthor()->getEmail());
		$item->setPubdate(date("U",strtotime($post["date_creation"],time())));
		$item->setUniqueId($post["idarticles"]);
		$item->setDescription($post["description"]);
	
		$feed->addItem($item);
	  }
	
	  $this->feed = $feed;
  }
  public function executePrint(sfWebRequest $request)
  {
	  $q = Doctrine_Query::create()
	 	->from('assoplatform n')
		->leftJoin('n.Articles c')
		->leftJoin('n.Plateformversiongroup')
		->leftJoin('n.Plateformversiongroup_5')
		->leftJoin('c.Tags')
		->leftJoin('n.Platform')
		->leftJoin('n.Platform_4')
		->where("n.idassoplatform = ?",$request->getParameter("id"));
		$articles = $q->execute();
		$this->article = $articles[0];
		
		$q = Doctrine_Query::create()
		->from('revisions n')
		->leftJoin('n.Assoplatform ap')
		->leftJoin('n.Flags f')
		->leftJoin('f.Defsflags')
		//->where('n.validate = ?', '1')
		->andwhere('n.id_asso_platform = ?', $request->getParameter("id"))
		->orderBy('n.idrevisions desc');
		
		$this->revisions = $q->execute();
		//echo var_dump(md5($this->revisions[0]["idrevisions"]));
		$this->revision = $this->revisions[0];
		$texte = file_get_contents("revisions/".$request->getParameter("id")."_".$this->revisions[0]["idrevisions"].".txt");
		$this->texte = $texte;
  }
}
